#pragma once 
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "../comm/util.hpp"
#include "../comm/log.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;

    class Compiler{
    public:
        Compiler()
        {}
        ~Compiler()
        {}
    public:
        static bool Compile(const std::string filename)
        {
            pid_t id = fork();
            if(id < 0)
            {
                LOG(ERROR) << "内部错误，创建子进程失败" << "\n";
                return false;
            }
            else if(id == 0)//子进程
            {
                umask(0);
                int _stderr = open(PathUtil::CompileError(filename).c_str(), O_CREAT | O_WRONLY, 0644);
                if(_stderr < 0)
                {
                    LOG(ERROR) << "没有成功形成stderr文件" << "\n";
                    exit(1);
                }
                dup2(_stderr, 2);
                // g++ -o tar src -std=c++11
                execlp("g++", "g++", "-o", PathUtil::Exe(filename).c_str(), PathUtil::Src(filename).c_str(), "-std=c++11", nullptr);
                LOG(ERROR) << "启动编译器g++失败，可能是参数错误" << "\n";
                exit(2);
            }
            else
            {
                waitpid(id, nullptr, 0);
                //是否编译成功
                if(!FileUtil::IsFilesExist(PathUtil::Exe(filename)))
                {
                    LOG("ERROR") << "编译失败, 没有形成可执行程序" << "\n";
                    return false;
                }
                LOG(INFO) << PathUtil::Src(filename) <<  "编译成功" << "\n";
                return true;
            }
        }

    };
}